<?php
// +----------------------------------------------------------------------
// | Author: wyd 2025/10/26
// | DESC: 热更新
// +----------------------------------------------------------------------

declare (strict_types=1);


namespace My\core\frame;

use Swoole\Process;

class HotReload
{
    private $md5File;

    public function run()
    {
        //官方规定
        return new Process(function () {
            //while(true) 官方规定
            while (true) {
                sleep(3); //间隔时间
                $md5Val = FileHelper::getFileMd5(ROOT_PATH.'/app/*',ROOT_PATH.'/app/config');

                //首次执行
                if ($this->md5File == '') {
                    $this->md5File = $md5Val;
                    continue;
                }

                //文件有改动，比较2个md5的值
                //直接热加载即可，而不是单独加载变更的文件
                if (strcmp($this->md5File, $md5Val) !== 0) {
                    echo 'reloading...'.PHP_EOL;
                    $pid = intval(file_get_contents(__DIR__ . '/myswoole.pid'));
                    if ($pid && $pid != 0) {
                        //重启，规定信号为SIGUSR1
                        \Swoole\Process::kill($pid,SIGUSR1);
                    }
                    $this->md5File = $md5Val;
                    echo 'reloaded'.PHP_EOL;
                }

            }
        });
    }

}